package com.comtime.smartbox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.comtime.greendaodemo.OpenLockInfo;
import com.comtime.greendaodemo.RemindInfo;
import com.comtime.greendaoutils.DataBaseUtil;
import com.comtime.home.MapActivity;
import com.comtime.service.MyService;
import com.comtime.smartbox.BaseActivity;
import com.comtime.smartkilimanjaro.R;
import com.comtime.utils.MySharedPreferences;
import com.comtime.view.MyDialog;
import com.comyou.customviews.SlideListView;

public class Activity_4 extends BaseActivity {
    HBApplication application;
    SlideListView slideListView;
    Button btn_edit;// 编辑
    Button btn_delete_all;// 删除全部

    RelativeLayout relate_delete;


    HashMap<Integer, Integer> choiceList = new HashMap<Integer, Integer>();
    ArrayList<OpenLockInfo> openLockInfos = new ArrayList<OpenLockInfo>();
    DataBaseUtil dataBaseUtil;
    MySharedPreferences mySharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);application = (HBApplication) getApplication();
		setContentView(R.layout.activity_4);
		dataBaseUtil = DataBaseUtil.getInstance(this);
		mySharedPreferences=MySharedPreferences.getInstance(this);
		init();
		regist();
		
		if(	 application.swDevicesList.get(0).isConnected()){
			 application.swDevicesList.get(0).sendUnlockRecordQuery();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	void init() {
		slideListView = (SlideListView) findViewById(R.id.listview);
		slideListView.setAdapter(adapter);// 绑定Adapter
		slideListView.setRightBtnWidth(dp2px(70));
		slideListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(Activity_4.this, MapActivity.class);
				intent.putExtra(MyService.VALUE_TAG, 0);
				intent.putExtra(MyService.VALUE_INFO, 0);
				startActivity(intent);
			}
		});
		btn_edit = (Button) findViewById(R.id.btn_edit);
		btn_delete_all = (Button) findViewById(R.id.btn_delete_all);
		relate_delete = (RelativeLayout) findViewById(R.id.relate_delete);
		relate_delete.setVisibility(View.INVISIBLE);
	}
	void regist() {
		IntentFilter filter = new IntentFilter(MyService.ACTION_UPDATE_UI);
		
		filter.addAction(MyService.ACTION_Get_OpenLockInfo); 
		registerReceiver(receiver, filter);
	}
	String action = "";
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			action = intent.getAction();
//			if (action.equals(MyService.ACTION_UPDATE_UI)) {
//				updateUI();
//			} 
			
			if(action.equals(MyService.ACTION_Get_OpenLockInfo)){
				openLockInfos=(ArrayList<OpenLockInfo>) intent.getSerializableExtra(MyService.Extra_OpenLockInfo);
				slideListView.deleteItem();
 				adapter.notifyDataSetChanged();
				
			}
			

		}
	};
	public void BackAction(View view) {
		this.finish();
		overridePendingTransition(R.anim.enter_left, R.anim.exit_right);
	}
//	/**
//	 * 改变界面
//	 */
//	void updateUI() {
//		choiceList.clear();
//		if (openLockInfos != null) {
//			openLockInfos.clear();
//			adapter.notifyDataSetChanged();
//		}
//		openLockInfos =  dataBaseUtil.loadOpenLockInfoByUpshow(mySharedPreferences.getUserId(), mySharedPreferences.getBluAdress());
//		slideListView.deleteItem();
//		adapter.notifyDataSetChanged();
//	}

    /**
     * 编辑或取消
     */
    boolean edit_flag = true;

    public void EditAction(View v) {
        edit_flag = !edit_flag;
        if (edit_flag) {
            btn_edit.setText(getText(R.string.edit));
            btn_delete_all.setVisibility(View.INVISIBLE);
            relate_delete.setVisibility(View.INVISIBLE);
        } else {
            btn_delete_all.setVisibility(View.VISIBLE);
            btn_edit.setText(getText(R.string.cancel));
            relate_delete.setVisibility(View.VISIBLE);
            if (choiceList != null) {
                choiceList.clear();
            }

        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 选中全部
     */
    public void SelectAllAction(View v) {

        for (int i = 0; i < openLockInfos.size(); i++) {
            choiceList.put(i, i);
        }
        adapter.notifyDataSetChanged();
    }

	/**
	 * 删除选中的
	 * 
	 * @param v
	 */
	public void ChoiceRemoveAction(View v) {
		if(choiceList.size()>0){
			Iterator it=choiceList.entrySet().iterator();           
			String key;           
			int value;   
			ArrayList<OpenLockInfo> lockInfos=new ArrayList<OpenLockInfo>();
			while(it.hasNext()){    
			        Map.Entry entry = (Map.Entry)it.next();           
			        key=entry.getKey().toString();           
			        value=(Integer) entry.getValue();    
			        
			        
			        lockInfos.add(openLockInfos.get(value));
			        
			}   
			choiceList.clear();
			openLockInfos.removeAll(lockInfos);
			adapter.notifyDataSetChanged();
			slideListView.deleteItem();
			saveDB(lockInfos);
		}
		
		
		
		
	}
	
	void saveDB(ArrayList<OpenLockInfo> lockInfos){
		for(int i=0;i<lockInfos.size();i++){
			OpenLockInfo openLockInfo=lockInfos.get(i);
			if(openLockInfo.getLock_id()>0){
				openLockInfo.setUpflag(2);
				dataBaseUtil.saveOpenLockInfo(openLockInfo);
			}else{
				dataBaseUtil.deleteOpenLockInfo(openLockInfo);
			}
		}
	}
	

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    int deletePosition = 0;
    BaseAdapter adapter = new BaseAdapter() {

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            ViewHolder holder = null;
            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(parent.getContext()).inflate(
                        R.layout.list_item_history, null);
                // 得到控件对象

                holder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                holder.tv_mode = (TextView) view.findViewById(R.id.tv_mode);
                holder.tv_address = (TextView) view
                        .findViewById(R.id.tv_address);
                holder.image_check = (ImageView) view
                        .findViewById(R.id.image_check);
                holder.relate_address = (RelativeLayout) view
                        .findViewById(R.id.relate_address);

                holder.ib_delete = (Button) view.findViewById(R.id.ib_delete);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.ib_delete.setTag(position);
            holder.ib_delete.setOnClickListener(onClickListener);

            holder.image_check.setTag(position);
            holder.image_check.setOnClickListener(onClickListener);

			
			
			
			OpenLockInfo lockInfo=openLockInfos.get(position);
			
			holder.tv_time.setText(lockInfo.getTime());
			holder.tv_address.setText(lockInfo.getAddress());
			// holder.relate_address.setTag(position);
			// holder.relate_address.setOnClickListener(onClickListener);
			//0x46对应的 ascII "F" 
			//0x42对应的 ascII "B" 
			if(lockInfo.getStyle()==0x46){
				holder.tv_mode.setText(getString(R.string.unlock_mode_F));
			}else{
				holder.tv_mode.setText(getString(R.string.unlock_mode_B));
			}
	
			if (!edit_flag) {
				holder.image_check.setVisibility(View.VISIBLE);
				holder.ib_delete.setVisibility(View.GONE);
				if (choiceList.containsKey(position)) {
					holder.image_check
							.setImageResource(R.drawable.icon_btn_choose_on);
				} else {
					holder.image_check
							.setImageResource(R.drawable.icon_btn_choose_off);
				}

            } else {
                holder.image_check.setVisibility(View.GONE);
                holder.ib_delete.setVisibility(View.VISIBLE);
            }
            return view;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return openLockInfos == null ? 0 : openLockInfos.size();
        }

        OnClickListener onClickListener = new OnClickListener() {

            @Override
            public void onClick(View view) {
                int get_position = (Integer) view.getTag();

                switch (view.getId()) {
                    case R.id.image_check:
                        if (choiceList.containsKey(get_position)) {
                            choiceList.remove(get_position);
                        } else {
                            choiceList.put(get_position, get_position);
                        }
                        notifyDataSetChanged();
                        break;
                    case R.id.ib_delete:
                        deletePosition = (Integer) view.getTag();
                        showDeleteDialog(getText(R.string.delete_remind).toString());
                        break;
                    default:
                        break;
                }

            }
        };

    };

    private class ViewHolder {
        TextView tv_mode, tv_time, tv_address;
        ImageView image_check;
        RelativeLayout relate_address;
        Button ib_delete;
    }

    // 确定删除
    void showDeleteDialog(String str) {
        final MyDialog myDialog = new MyDialog(Activity_4.this);
        myDialog.setContent(str);
        myDialog.getLeftButton().setText(getText(R.string.cancel));
        myDialog.getRighrButton().setText(getText(R.string.ok));
        myDialog.getLeftButton().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                myDialog.dismiss();

            }
        });
        myDialog.getRighrButton().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myDialog.dismiss();
				// 删除记录
				OpenLockInfo openLockInfo = openLockInfos.get(deletePosition);
				if (openLockInfo.getLock_id() > 0) {
					openLockInfo.setUpflag(2);
					dataBaseUtil.saveOpenLockInfo(openLockInfo);
				} else {
					dataBaseUtil.deleteOpenLockInfo(openLockInfo);
				}
				openLockInfos.remove(deletePosition);
				slideListView.deleteItem();
				adapter.notifyDataSetChanged();

            }
        });

        myDialog.show();
    }
}
